<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学习提醒</title>
    <style>
        .container {
            text-align: center;
        }

        .config {
            display: inline;
        }

        .number {
            width: 50px;
        }

        /* 隐藏最小化按钮 */
        ::-webkit-window-controls-overlay {
            display: none !important;
        }

    </style>
</head>
<body>
<div class="container">
    <audio id="goLook" src="./go look.mp3"></audio>
    <audio id="goRest" src="./go rest.mp3"></audio>
    <audio id="lookStopToStudy" src="./look stop to study.mp3"></audio>
    <audio id="restStopToStudy" src="./rest stop to study.mp3"></audio>
    <audio id="start" src="./start.mp3"></audio>
    <audio id="stop" src="./stop.mp3"></audio>
    <audio id="lookStopToRest" src="./look stop to rest.mp3"></audio>
    <audio id="restStopToLook" src="./rest stop to look.mp3"></audio>
    <div class="config">
        <label for="restTime">播报次数</label>
        <input type="number" class="number" id="readTimes" min="1" value="5">次
        <br>
    </div>
    <div class="config">
        <label for="restTime">每学习</label>
        <input type="number" class="number" id="restTime" min="1">分钟
        <label for="restTimeDuration">, 休息</label>
        <input type="number" class="number" id="restTimeDuration" min="1">分钟<br>
    </div>
    <div class="config">
        <label for="lookAwayTime">每学习</label>
        <input type="number" class="number" id="lookAwayTime" min="1">分钟
        <label for="lookAwayDuration">, 远眺</label>
        <input type="number" class="number" id="lookAwayDuration" min="1">分钟<br>
    </div>
    <div style="margin-top:8px;">
        <button onclick="startStudy()">开始学习</button>
        <button onclick="stopStudy()">暂停学习</button>
        <button onclick="stopRead()">停止播报</button>
    </div>
    <div style="margin-top:8px;" id="timer"></div>

</div>
<script type="text/javascript" src="./workerInterval.js"></script>
<script>
    // 播报次数
    let readTimes = 1;
    // 休息间隔时间
    let restTime = 0;
    // 休息时长
    let restTimeDuration = 0;
    // 远眺间隔时间
    let lookAwayTime = 0;
    // 远眺持续时间
    let lookAwayDuration = 0;
    // 开始学习时间
    let startStudyTime = 0;
    let timeClock;
    // 当前操作
    let actionName = "远眺"
    // 总计真实休息时间, 一直会累加
    let realRestTime = 0;
    // 学习时间, 一直累加
    let realStudyTime = 0;
    // 只要开始学习,就会累计学习积分
    let availableTime = 0;
    // 只要开始学习,就会累计学习积分
    let availableTimeLook = 0;
    // 倒计时时间
    let donwTime = 0;

    let next_action = []

    let last_next_action = undefined

    /**
     * 分钟钟表, 每分检查一次应该下一步干什么
     */
    function calcMinTask() {
        if (donwTime !== 0) {
            return
        }
        let restFlag = realStudyTime % restTime === 0
        let lookAwayFlag = realStudyTime % lookAwayTime === 0

        if (lookAwayFlag && availableTimeLook >= lookAwayTime) {
            console.log("添加远眺任务")
            next_action.push({
                name: "结束远眺",
                duration: lookAwayDuration
            })
            availableTimeLook -= lookAwayTime
        }

        // 达到休息条件
        if (restFlag && availableTime >= restTime) {
            console.log("添加休息任务")
            next_action.push({
                name: "结束休息",
                duration: restTimeDuration
            })
            availableTime -= restTime
        }

        let actionObj = next_action.shift()
        if (actionObj) {
            console.log("执行任务: " + actionObj.name)
            incDownTime(actionObj.name, actionObj.duration)
            last_next_action = actionObj
        } else {
            console.log("最近没有休息, 重新显示下次休息时间")
            calcNextAction()
            if (last_next_action.name === '结束休息') {
                notifyText("休息结束，回来学习了!")
                playAudio("restStopToStudy", readTimes)
            } else if (last_next_action.name === '结束远眺') {
                notifyText("远眺结束，回来学习了!")
                playAudio("lookStopToStudy", readTimes)
            }
            last_next_action = undefined
        }
    }

    function incDownTime(a, d) {
        actionName = a
        donwTime += d;
        if (a === "结束休息") {
            if (last_next_action && last_next_action.name === '结束远眺') {
                notifyText("远眺结束，休息一会吧!")
                playAudio("lookStopToRest", readTimes)
            } else {
                notifyText("休息一会吧!")
                playAudio("goRest", readTimes)
            }
        } else {
            if (last_next_action && last_next_action.name === '结束休息') {
                notifyText("休息结束，远眺一会!")
                playAudio("restStopToLook", readTimes)
            } else {
                notifyText("放松一下眼睛吧!")
                playAudio("goLook", readTimes)
            }
        }
    }

    let globalSeconds = 0
    let stop = false

    function createClock() {
        timeClock = new WorkerInterval(function () {
            if (!stop) {
                let runTimeMinutes = Math.floor(globalSeconds / 60);
                let minutes = Math.floor(donwTime / 60);
                let seconds = donwTime % 60;
                if (donwTime > 0) {
                    document.getElementById('timer').innerHTML = `已学习${Math.floor(realStudyTime / 60)}分钟, 已休息${Math.floor(realRestTime / 60)}分钟 <br>距离${actionName}还有 ${minutes} 分钟 ${seconds} 秒`;
                    // document.getElementById('timer').innerHTML = `已运行${runTimeMinutes}分钟, 已学习${Math.floor(realStudyTime / 60)}分钟 <br><br> 距离${actionName}还有 ${minutes} 分钟 ${seconds} 秒`;
                    donwTime--;
                    // 表示在学习
                    if (actionName.indexOf("结束")) {
                        realStudyTime++
                        availableTime++
                        availableTimeLook++
                        console.log("学习:" + realStudyTime)
                        // 表示在休息或远眺
                    } else if (actionName.indexOf("开始")) {
                        realRestTime++
                        console.log("休息:" + realRestTime)
                    }
                }
                if (globalSeconds !== 0 && globalSeconds % 60 === 0) {
                    calcMinTask()
                }
                globalSeconds++
            }
        }, 1000);
    }

    function stopStudy() {
        if (stop) {
            return
        }
        notifyText("暂停学习!")
        playAudio("stop")
        stop = true;
    }

    function startStudy() {
        /*if (new Date().getTime() > 1710691200000) {
            return;
        }*/
        if (stop) {
            notifyText("开始学习!")
            playAudio("start")
            stop = false;
        } else {
            if (startStudyTime === 0) {
                notifyText("开始学习!")
                playAudio("start")
                startStudyTime = parseInt(new Date().getTime() / 1000);
                readTimes = parseInt(document.getElementById('readTimes').value);
                restTimeDuration = parseInt(document.getElementById('restTimeDuration').value) * 60;
                restTime = parseInt(document.getElementById('restTime').value) * 60;
                lookAwayDuration = parseInt(document.getElementById('lookAwayDuration').value) * 60;
                lookAwayTime = parseInt(document.getElementById('lookAwayTime').value) * 60;
                if (restTime <= 0 || restTime <= 0 || lookAwayTime <= 0 || lookAwayDuration <= 0) {
                    alert("请输入有效的数值。");
                    return;
                }
                calcNextAction()
                createClock();
            }
        }
    }

    function calcNextAction() {
        let lookDiff = availableTimeLook - lookAwayTime
        let restDiff = availableTime - restTime
        if (restDiff <= lookDiff) {
            actionName = "开始远眺";
            donwTime = Math.abs(lookDiff)
        } else {
            actionName = "开始休息";
            donwTime = Math.abs(restDiff)
        }
    }


    const notifier = require('node-notifier');

    var stopReadFlag = false
    function stopRead(){
        stopReadFlag = true
        setTimeout(()=> stopReadFlag = false, 3000 * readTimes)
    }


    function playAudio(mark, times = 1) {
        let newTime = times;
        if(stopReadFlag){
           return;
        }
        document.querySelector("#" + mark).play();
        if (--newTime > 0) {
            setTimeout(() => playAudio(mark, newTime), 3000)
        }
    }

    function notifyText(text) {
        console.log(text)
        try {
            // 发送通知
            notifier.notify({
                appName: '学习提醒',
                title: '通知',
                icon: './icon.png',
                message: text,
                closeLabel: '关闭',
                timeout: 3
            });
        }catch(e) {
            console.error("非nw环境")
        }
    }

    try {
        // 获取window对象
        var win = nw.Window.get();
        win.setResizable(false)
        win.setMaximumSize(320, 170)
        win.setMinimumSize(320, 170)
        // 监听最小化事件
        /*win.on('minimize', function () {
            win.show()
            notifyText("为了保证正常通知，窗口不能最小化")
        });*/

        // 监听最大化事件
        win.on('maximize', function () {
            win.resize(320, 170)
        });

        // 监听最大化事件
        win.on('zoom', function () {
            win.resize(320, 170)
        });
    } catch (e) {
        console.error("非nw环境")
    }

    // https://nwjs-cn.readthedocs.io/zh-cn/latest/References/Manifest%20Format/index.html
</script>
</body>
</html>
